/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    Platform,
    StyleSheet,
    Text,
    View, TouchableOpacity, Image, ScrollView, processColor, NativeAppEventEmitter
} from 'react-native';
import  theme from '../config/theme'
import {px2dpH, px2dpW} from "../config/px2dp"
import Chart from "../widget/Chart"
import  ChartConfig from '../config/ChartConfig'
type Props = {};
import _ from 'lodash';
const purple = processColor('#8A2BEA')
const green = processColor('#00ff00');
const yellow = processColor('#ffff00');
const red = processColor('#ee7733');

import net from 'react-native-tcp';
import  TcpManager from "../manager/TcpManager"
import  ProtobufJsManager from "../proto/ProtobufJsManager"
import OrientationUtil from '../util/OrientationUtil'
import RNFS from 'react-native-fs';

import ModalListDialogHome from '../widget/ModalListDialogHome'
import Spinner from 'react-native-loading-spinner-overlay'
import UtilManager from '../util/UtilManager'


var Sound = require('react-native-sound');
export default class HomeScene extends Component<Props> {
    static navigationOptions = ({navigation}) => ({
        headerTitle: '鼻鼾检测仪',
        headerStyle: theme.headerStyle,
        headerLeft: (
            <TouchableOpacity style={{marginLeft:px2dpW(8)}} onPress={()=> navigation.state.params.clickLeft()}>
                <Image
                    style={{width:px2dpH(32),height:px2dpH(32)}}
                    source={require('../img/icon-10-setting.png')}/>
            </TouchableOpacity>),
        headerRight: (
            <TouchableOpacity style={{marginRight:px2dpW(8)}} onPress={()=> navigation.state.params.clickRight()}>
                <Image
                    style={{width:px2dpH(32),height:px2dpH(32)}}
                    source={require('../img/icon-10-setting.png')}/>
            </TouchableOpacity>),
    });


    constructor(props) {
        super(props)

        this.state = {
            reload: false,
        }


        // this.chartTitle = "05/30 10:00-05/30 23:00";
        //  this.btnBarOnClick = this.btnBarOnClick.bind(this)


        this.sSeries = []
        this.wenshidu = {}
        this.fenbeidata = {}


        this.bottomtext = [1, 2, 3]
        this.listDialogvisable = false
        console.log("zzz", (parseInt(new Date().getTime() / 1000)).toString(16))

        this.inter = 0
        this.maxs = 0
        this.leftright = 0;
    }

    showChartData() {


        if (theme.datatrue) {
            // this.visible = true
            // this.reload()
            let n = 200;
            switch (theme.datainfo.groups) {
                case 1:
                    this.sSeries = [ChartConfig.getData(theme.yvalue1, n, true)]
                    break
                case 2:
                    this.sSeries = [ChartConfig.getData(theme.yvalue1, n, true), ChartConfig.getData(theme.yvalue2, n, true)]
                    break
                case  3:
                    this.sSeries = [ChartConfig.getData(theme.yvalue1, n, true), ChartConfig.getData(theme.yvalue2, n, true), ChartConfig.getData(theme.yvalue3, n, true)]
                    break
            }
            if (theme.air && theme.temp && theme.wet) {
                this.wenshidu = ChartConfig.getDataThree(theme.air, theme.temp, theme.wet, 1, false)
            }
            if (theme.db) {
                this.fenbeidata = (ChartConfig.getDataLine(theme.db, 1, false))
            }

            this.visible = false
            this.reload()
        } else {
            console.log("data is not true")
        }


    }

    disShowChartData() {
        this.sSeries = []
        this.wenshidu = {}
        this.fenbeidata = {}
        this.reload()
    }


    reload() {
        this.setState({reload: !this.state.reload})
    }

    sub() {
        this._fousListener = this.props.navigation.addListener('didFocus', () => {
            console.log("_fousListener")
            OrientationUtil.screenLockToPortrait()
        });
        this._blurListener = this.props.navigation.addListener('willBlur', () => {
            console.log("_blurListener")
        });
    }

    unsub() {
        this._fousListener.remove();
        this._blurListener.remove();
    }


    componentDidMount() {
        this.sub()

        this.props.navigation.setParams({clickRight: this.goToSetting.bind(this), clickLeft: this.goTestTcp.bind(this)})
        this.reload()

        // ProtobufJsManager.parseMessage("08011008422C0803120C120A617564696F312E776176120C120A617564696F322E776176120C120A617564696F332E776176", ProtobufJsManager.headerType.SnapDevice).then((result) => {
        //     console.log('GET DATA RESULT FROM DEVICE', result);
        // }, (error) => {
        //     console.log("error=" + error)
        // });


        //  08011008422C0803120C120A617564696F312E776176120C120A617564696F322E776176120C120A617564696F332E776176
        this.readDataInfo("snapinfo.txt")
        //   this.readDataEnv("snapenvdata")

        //  this.readDataWav("snapwav.txt")
        // this.writeFile()


        // this.writeFileSc("zzzz","test.txt")
    }

    writeFileSc(data, name) {
        //  create a path you want to write to
        const path = theme.getPath(name)//(Platform.OS === 'ios' ? RNFS.MainBundlePath : RNFS.ExternalStorageDirectoryPath ) + '/' + name + '.txt';

        //write the file
        return new Promise((fulfill, reject) => {
            RNFS.writeFile(path, data, 'utf8')
                .then((success) => {
                    console.log('writeFile path', path);
                    fulfill(path)
                })
                .catch((err) => {
                    console.log(err.message);
                    reject(err.message)
                });
        })

    }

    componentWillUnmount() {
        //反注册广播
        this.releaseWav()

    }

    writeFile() {
        const path = theme.getPath("test.txt");

        return RNFS.writeFile(path, '新添加的文本', 'utf8')
            .then((success) => {
                console.log('write success');


                RNFS.readFile(path)
                    .then((result) => {
                        console.log("read file", result);


                    })
                    .catch((err) => {
                        console.log("err", err.message);


                    });
            })
            .catch((err) => {
                console.log(err.message);

            });


    }

    appendFile() {
        const path = theme.getPath("test.txt");

        return RNFS.appendFile(path, '新添加的文本', 'utf8')
            .then((success) => {
                console.log('success');

            })
            .catch((err) => {
                console.log(err.message);

            });
    }

    readDataWav(name) {
        const path = theme.getPath(name);

        return RNFS.readFile(path)
            .then((result) => {
                console.log("readWav", result);
                let data2 = result.substring(46, result.length)
                console.log("data2", data2)


                UtilManager.createFileWithByte(data2, theme.getPath(name + '.wav')).then((suc) => {
                    console.log("suc", suc)
                }, (fail) => {
                    console.log("error", fail)
                })

            })
            .catch((err) => {
                console.log("err", err.message);
                console.log("data wav 当前没有音频");


            });
    }

    readDataInfo(name) {
        // create a path you want to delete

        this.visible = true
        this.reload()
        const path = theme.getPath(name);

        return RNFS.readFile(path)
            .then((result) => {
                console.log("readFile", result);
                theme.datainfo = {
                    "start": parseInt(result.split("&")[0], 16),
                    "timelength": parseInt(result.split("&")[1]),
                    "rate": parseInt(result.split("&")[2]),
                    "groups": parseInt(result.split("&")[3])
                }


                theme.calcuTimeList()

                console.log(theme.datainfo)

                this.readWav("snapwavlist.txt")
                this.readData("snapdata.txt")


            })
            .catch((err) => {
                console.log("err", err.message);
                console.log("datainfo  当前并没有保存过数据");
                this.visible = false
                this.reload()

            });
    }

    readWav(name) {
        const path = theme.getPath(name);
        return RNFS.readFile(path)
            .then((result) => {
                console.log("readWavlist", result);
                theme.wav = []
                let m = result.split("&")
                for (let i = 0; i < m.length; i++) {
                    console.log(parseInt(m[i], 16))
                    let s = {
                        "name": m[i],
                        "title": theme.timeStampToDateTitle(parseInt(m[i], 16) * 1000),
                        "path": theme.getPath(m[i] + ".wav")
                    }
                    theme.wav.push(s)
                }
                console.log("theme.wav", theme.wav)

            })
            .catch((err) => {
                console.log("err", err.message);
                console.log("data wav 当前并没有保存过数据");


            });
    }

    readData(name) {
        // create a path you want to delete
        const path = theme.getPath(name);

        return RNFS.readFile(path)
            .then((result) => {
                console.log("readFile", result);

                // this.chartTitle=result
                // this.reload()
                //23363a 3562343336663361  3034   3031   3030303945333537

                console.log("datalength", result.length)
                console.log("data1", result.substring(0, 46))
                let dataheader = result.substring(0, 46)

                let timestart = theme.getHexFromAscii(dataheader.substring(6, 22))


                let loopcount = theme.getHexFromAscii(dataheader.substring(22, 26))

                let groups = theme.getHexFromAscii(dataheader.substring(26, 30))

                let length = theme.getHexFromAscii(dataheader.substring(30, 46))


                console.log(loopcount, timestart, groups, parseInt(length, 16))


                console.log("data2", result.substring(46, result.length))

                theme.datatrue = true
                let data = theme.splitByConLength(result.substring(46, result.length), 4)

                theme.yvalue1 = []
                theme.yvalue2 = []
                theme.yvalue3 = []
                switch (theme.datainfo.groups) {
                    case 1:
                        for (let i = 0; i < data.length / theme.datainfo.groups / 2; i++) {
                            theme.yvalue1.push(this.getResult(parseInt(data[i * theme.datainfo.groups * 2 + 1], 16), parseInt(data[i * theme.datainfo.groups * 2], 16)))
                            let data = theme.splitByConLength(result.substring(46, result.length), 4)
                        }
                        break
                    case 2:
                        for (let i = 0; i < data.length / theme.datainfo.groups / 2; i++) {
                            theme.yvalue1.push(this.getResult(parseInt(data[i * theme.datainfo.groups * 2 + 1], 16), parseInt(data[i * theme.datainfo.groups * 2], 16)))
                            theme.yvalue2.push(this.getResult(parseInt(data[i * theme.datainfo.groups * 2 + 3], 16), parseInt(data[i * theme.datainfo.groups * 2 + 2], 16)))
                        }
                        break
                    case 3:
                        console.log("y3----------------------->")
                        for (let i = 0; i < data.length / theme.datainfo.groups / 2; i++) {
                            theme.yvalue1.push(this.getResult(parseInt(data[i * theme.datainfo.groups * 2 + 1], 16), parseInt(data[i * theme.datainfo.groups * 2], 16)))
                            theme.yvalue2.push(this.getResult(parseInt(data[i * theme.datainfo.groups * 2 + 3], 16), parseInt(data[i * theme.datainfo.groups * 2 + 2], 16)))
                            theme.yvalue3.push(this.getResult(parseInt(data[i * theme.datainfo.groups * 2 + 1 + 5], 16), parseInt(data[i * theme.datainfo.groups * 2 + 4], 16)))
                        }


                        break
                }


                theme.getAverSeries();

                this.readDataEnv("snapenvdata.txt")


            })
            .catch((err) => {
                console.log("err", err.message);
                console.log("data 当前并没有保存过数据");


            });
    }

    getResult(s1, s2) {

        if (s1 > s2) {
            this.inter = (s1 - s2) * 1.0 / s1
            this.maxs = s1
            this.leftright = 1

        } else if (s1 < s2) {
            this.inter = (s2 - s1) * 1.0 / s2
            this.maxs = s2
            this.leftright = -1
        } else {
            return 0
        }

        return 1.6667 * this.leftright * 0.1314 * this.maxs * (1 - this.inter / 3.024) * Math.sqrt((this.inter / (this.maxs * 300)));
    }

    readDataEnv(name) {
        // create a path you want to delete
        const path = theme.getPath(name)

        return RNFS.readFile(path)
            .then((result) => {
                console.log("readDataEnv", result);


                //  let dataheader = result.substring(0, 46)


                console.log("data2", result.substring(46, result.length))

                let data = theme.splitByConLength(result.substring(46, result.length), 4)
                theme.air = []
                theme.temp = []
                theme.wet = []
                theme.db = []

                console.log("datalength", data.length)

                for (let i = 0; i < data.length / 4 - 1; i++) {
                    theme.air.push(parseInt(data[i * 4], 16) / 100)
                    theme.temp.push(parseInt(data[i * 4 + 1], 16) / 100)
                    theme.wet.push(parseInt(data[i * 4 + 2], 16) / 10)
                    theme.db.push(parseInt(data[i * 4 + 3], 16))
                }

                theme.getAverEnv()

                this.showChartData()


            })
            .catch((err) => {
                console.log("err", err.message);
                console.log("data env 当前并没有保存过数据");
                this.showChartData()


            });
    }


    goTestTcp() {
        console.log("goTestTcp")
        //       this.play()
    }

    goToSetting() {
        console.log("goToSetting")
        this.disShowChartData()
        this.props.navigation.navigate("GetDataScene")
    }


    goToScan(text) {

        console.log("goToScan")
        this.disShowChartData()
        this.props.navigation.navigate("ScanCodeScene", {"type": text})
        // this.props.navigation.navigate("ScanCodeResultScene", {"type": text})

    }

    format01List(list) {
        let newlist = [];


        for (let i = 0; i < list.length - 1; i++) {
            newlist.push(list[i])
            if (list[i] != list[i + 1]) {
                newlist.push({x: i + 1, y: list[i].y})
            }

        }
        return newlist
    }

    _random01(range: number, size: number) {
        let list = [];
        for (let i = 0; i < size; i++) {
            list.push({x: i, y: Math.random() < 0.5 ? 0 : 1})
        }
        return list

    }

    _randomYValues(range: number, size: number) {
        let list = [];
        for (let i = 0; i < size; i++) {
            list.push({x: i, y: Math.random() * range - range / 2})
        }
        return list
    }


    handleSelect(event) {
        let entry = event.nativeEvent
        if (entry == null) {
            this.setState({...this.state, selectedEntry: null})
        } else {
            this.setState({...this.state, selectedEntry: JSON.stringify(entry)})
        }

        console.log(event.nativeEvent)
    }

    onChange(event) {
        console.log(event)
    }


    btnBarOnClick(text) {
        console.log(text)
        this.goToScan(text)
    }

    fenBeiOnRight() {
        console.log("fenBeiOnRight");
        this.dialogShow()

        //    TcpManager.client.write("测试");
    }

    dialogShow() {
        this.listDialogvisable = true
        this.reload()
    }

    dialogCancel() {
        this.listDialogvisable = false
        this.releaseWav()
        this.reload()
    }

    play() {
        console.log("play")

        //     this.s && this.s.setNumberOfLoops(-1);
        this.s && this.s.play((success) => {
            if (success) {
                console.log('successfully finished playing');
            } else {
                console.log('playback failed due to audio decoding errors');
                // reset the player to its uninitialized state (android only)
                // this is the only option to recover after an error occured and use the player again
                this.s && this.s.reset();
            }
        });
    }

    releaseWav() {
        this.s && this.s.pause()
        this.s && this.s.stop()
        this.s && this.s.release()
    }

    onWavItemClick(index) {
        console.log("onWavItemClick", index)

        this.releaseWav()

        this.s = new Sound(theme.wav[index].path, null, (e) => {
            if (e) {
                console.log('播放失败');
                return;
            }
            this.play()
            // s.play(() => s.release());
        });
    }

    chartClick(name) {
        console.log("name", name)
        this.disShowChartData()
        this.props.navigation.navigate("DetailChartScene", {name: name})
    }

    componentWillMount() {
//todo NativeAppEventEmitter.emit('aaa', 'aaa') 下个返回的页面需调这个
        NativeAppEventEmitter.addListener('gobacktohome', (e) => {
            console.log('HomeScene--------------DeviceEventEmitter')
            if (!theme.datatrue) {
                this.readDataInfo("snapinfo.txt")
            } else {
                this.showChartData()
            }

            //
        })


        // let t = '#3:192.168.001.135&mysncode'
        // let split1 = t.split("&")
        // let sn = split1[1]
        // let ip = split1[0].substring(2, split1[0].length)
        // console.log("sn", sn)
        // console.log("ip", ip)
    }

    componentWillUnmount() {
        this.unsub()
        this.camera = null;
        NativeAppEventEmitter.removeListener('gobacktohome')
    }


    renderButtonBar() {
        return (
            <View style={styles.btnbarbg}>
                <TouchableOpacity onPress={this.btnBarOnClick.bind(this,"快速检测")}
                                  style={styles.btnbg}>
                    <Text style={styles.btntext}>快速检测</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.btnBarOnClick.bind(this,"启动设备")}
                                  style={styles.btnbg}>
                    <Text style={styles.btntext}>启动设备</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.btnBarOnClick.bind(this,"查看数据")}
                                  style={styles.btnbg}>
                    <Text style={styles.btntext}>查看数据</Text>
                </TouchableOpacity>
            </View>)
    }

    renderScrolltable() {

        return (
            <ScrollView
                style={{ width:theme.screenWidth,flex: 1, backgroundColor: 'rgb(255,255,255)' }}
                contentContainerStyle={{alignItems:'center'}}>

                {this.sSeries.length == 0 ? null : <Text style={{padding:px2dpW(12)}}>{theme.homeTitle}</Text>}
                {this.sSeries.map((item, i) => (
                    <View key={i}>
                        <Chart
                            name={"S"+(i+1)}
                            ifThree={false}
                            containStyle={{ width:theme.screenWidth,height:px2dpH(220)}}
                            xAxis={ChartConfig.xAxisA}
                            yAxis={ChartConfig.yAxisA}
                            data={item}
                            onSelect={this.handleSelect.bind(this)}
                            onChange={this.onChange.bind(this)}
                            scaleEnabled={false}
                            scaleXEnabled={false}
                            scaleYEnabled={false}
                            pinchZoom={false}
                            chartDisClickable={false}
                            onChartPress={this.chartClick.bind(this,("S"+(i+1)))}
                            doubleTapToZoomEnabled={false}
                            bottomtext={theme.homebottomtext}
                            rightValue={i==0?theme.yvalue1aver:(i==1?theme.yvalue2aver:theme.yvalue3aver)}
                        />
                        <View style={{height:px2dpH(10),width:theme.screenWidth}}/>
                    </View>))}

                {this.sSeries.length == 0 ? null : <Chart
                        ifThree={true}
                        containStyle={{ width:theme.screenWidth,height:px2dpH(220)}}
                        xAxis={ChartConfig.xAxisA}
                        yAxis={ChartConfig.yAxisA}
                        data={this.wenshidu}
                        onSelect={this.handleSelect.bind(this)}
                        onChange={this.onChange.bind(this)}
                        scaleEnabled={false}
                        scaleXEnabled={false}
                        scaleYEnabled={false}
                        pinchZoom={false}
                        chartDisClickable={false}
                        onChartPress={this.chartClick.bind(this,"温湿度")}
                        doubleTapToZoomEnabled={false}
                        bottomtext={theme.homebottomtext}
                        rightValue={theme.envaver}
                    />}

                <View style={{height:px2dpH(10),width:theme.screenWidth}}/>
                {this.sSeries.length == 0 ? null : <Chart
                        name={"分贝计"}
                        ifThree={false}
                        ifCustomRight={true}
                        onRight={this.fenBeiOnRight.bind(this)}
                        containStyle={{ width:theme.screenWidth,height:px2dpH(220)}}
                        xAxis={ChartConfig.xAxisA}
                        yAxis={ChartConfig.yAxisA}
                        data={this.fenbeidata}
                        onSelect={this.handleSelect.bind(this)}
                        onChange={this.onChange.bind(this)}
                        scaleEnabled={false}
                        scaleXEnabled={false}
                        scaleYEnabled={false}
                        pinchZoom={false}
                        chartDisClickable={false}
                        onChartPress={this.chartClick.bind(this,"分贝")}
                        doubleTapToZoomEnabled={false}
                        bottomtext={theme.homebottomtext}
                    />}
                <ModalListDialogHome
                    _dialogVisible={this.listDialogvisable}
                    _dialogLeftBtnAction={()=> this.dialogCancel()}
                    _dialogRightBtnAction={()=> {}}
                    _dialogLeftBtnTitle={'取消'}
                    _dialogRightBtnTitle={'确定'}
                    itemClick={this.onWavItemClick.bind(this)}
                    list={theme.wav}
                />
                <Spinner visible={this.visible} textContent={"正在加载数据。。"} cancelable={true}/>
            </ScrollView>

        )
    }

    render() {
        return (
            <View style={styles.container}>
                {this.renderButtonBar()}

                {this.renderScrolltable()}
            </View>
        );
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#E5ECFF',
    },
    btnbarbg: {
        width: theme.screenWidth,
        height: px2dpH(60),
        backgroundColor: '#ffffff',
        marginTop: px2dpH(16),
        alignItems: 'center',
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginBottom: px2dpH(16),
    },

    btnbg: {
        width: px2dpW(100),
        height: px2dpH(40),
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'rgb(68,154,208)',
        borderRadius: px2dpW(4)
    },
    btntext: {
        color: '#ffffff',
        fontSize: 13
    },


    chart: {
        flex: 1
    }

});
